package dir_sync;

import javax.swing.*;
import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.Vector;

public class DirCompareWork implements Runnable {

    private final DefaultListModel<String> listModelSrc;
    private final DefaultListModel<String> listModelDst;
    private final JButton startCompareButton;
    private final JTextField dir1;
    private final JTextField dir2;
    private final boolean onlyShowDiff;
    private final int scanDeep;
    private final boolean bothDiff;
    private final JLabel statusLabel;
    private final JButton syncCopyButton;
    private final Vector<File> srcChangedFiles;

    public DirCompareWork(DefaultListModel<String> listModelSrc, DefaultListModel<String> listModelDst,
                          JButton startCompareButton,
                          JTextField dir1, JTextField dir2, boolean onlyShowDiff, int scanDeep, boolean bothDiff,
                          JLabel statusLabel, JButton syncCopyButton, Vector<File> srcChangedFiles) {
        this.listModelSrc = listModelSrc;
        this.listModelDst = listModelDst;
        this.startCompareButton = startCompareButton;
        this.dir1 = dir1;
        this.dir2 = dir2;
        this.onlyShowDiff = onlyShowDiff;
        this.scanDeep = scanDeep;
        this.bothDiff = bothDiff;
        this.statusLabel = statusLabel;
        this.syncCopyButton = syncCopyButton;
        this.srcChangedFiles = srcChangedFiles;
    }

    @Override
    public void run() {
        // 确保按钮文本更新在 EDT 中执行
        SwingUtilities.invokeLater(() -> startCompareButton.setText("停止比较"));

        Instant start = Instant.now();
        int srcDiff = 0;
        int dstDiff = 0;
        try {
            System.out.println("开始比较目录的不同---------------------------------------------------------------");

            FileCompare fc1 = new FileCompare(listModelSrc, validateDir(dir1.getText()), validateDir(dir2.getText()),
                    onlyShowDiff, scanDeep, statusLabel, srcChangedFiles);
            srcDiff = fc1.call();

            if (bothDiff) {
                FileCompare fc2 = new FileCompare(listModelDst, validateDir(dir2.getText()), validateDir(dir1.getText()), onlyShowDiff, scanDeep, statusLabel, srcChangedFiles);
                dstDiff = fc2.call();
            }

        } catch (Exception e) {
            if (e instanceof InterruptedException) {
                JOptionPane.showMessageDialog(null, "目录比较被用户中断");
            } else {
                JOptionPane.showMessageDialog(null, "目录比较过程中出现错误: " + e.getMessage());
            }
            System.err.println("ERROR: " + e.getMessage());
        } finally {
            Instant end = Instant.now();
            long duration = Duration.between(start, end).toMillis();

            // 显示比较结果
            int finalSrcDiff = srcDiff;
            int finalDstDiff = dstDiff;

            SwingUtilities.invokeLater(() -> {
                String time = duration + "毫秒";
                if (duration > 1000) {
                    time = duration / 1000 + "秒";
                }
                StringBuilder message = new StringBuilder();
                message.append("目录比较完毕！此次比较耗时：").append(time).append("！\r\n有关比较结果请关注结果列表框o(∩_∩)o \r\n");
                message.append("源目录差异数量： ").append(finalSrcDiff);
                if (bothDiff) {
                    message.append("\r\n目标目录差异数量： ").append(finalDstDiff);
                }
                JOptionPane.showMessageDialog(null, message);
                startCompareButton.setText("开始比较");
            });

            DirCompare.isComparing = false;
            statusLabel.setText("完成比较，发现源目录差异数量：" + finalSrcDiff + ", 目的目录差异数量：" + finalDstDiff);
            syncCopyButton.setEnabled(true);
        }
    }

    private File validateDir(String dirPath) {
        if (dirPath == null || dirPath.trim().isEmpty()) {
            throw new IllegalArgumentException("目录路径不能为空");
        }
        File dir = new File(dirPath);
        if (!dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException("无效的目录路径: " + dirPath);
        }
        return dir;
    }

}
